﻿using MahApps.Metro.Controls;
using Minecraft_Armor_Stand_Creater.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace Minecraft_Armor_Stand_Creater
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        public MainWindow()
        {
            Loaded += Main_Loaded;
            Closed += Main_Closed;

            InitializeComponent();

            Save_Button.Click += Save_Click;
            Option_Button.Click += Option_Click;
            About_Button.Click += About_Click;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Main_Loaded(object sender, RoutedEventArgs e)
        {
            Log.Write("全局初始化", LogType.Info);

            //删除更新文件
            ProgramConfig.KillProcess("MAS Updater", false);
            File.Delete(@"MAS Updater.exe");

            try
            {
                StreamReader test = new(WebRequest.Create("http://www.mcbbs.net/thread-580119-1-1.html").GetResponse().GetResponseStream(), Encoding.UTF8);
                Log.Write("测试访问成功", LogType.Info);
            }
            catch (Exception ex)
            {
                Log.Write($"测试访问失败{ex.Message}", LogType.Error);
            }

            LanguageConfig();
            GuidanceConfig();
            ThemeConfig();

            Log.Write("配置初始化成功", LogType.Info);

            VersionData.Instance.SearchVersion();

            _NavigationFrame.Navigate(SingleControls.Instance.ArmorStandPage);
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Main_Closed(object sender, EventArgs e)
        {
            Log.Write("正常关闭", LogType.Info);
            Environment.Exit(0);
        }

        /// <summary>
        /// 获取加载语言配置
        /// </summary>
        static void LanguageConfig()
        {
            try
            {
                ProgramConfig.Instance._langCN = bool.Parse(ConfigOperator.IniRead("System", "Lang"));
            }
            catch//读取失败则创建新配置
            {
                ConfigOperator.IniWrite("System", "Lang", true.ToString());
            }

            //语言配置生效
            ResourceDictionary LangDict = new();
            if (ProgramConfig.Instance._langCN)
                LangDict.Source = new Uri(@"Resource\Languages\CN.xaml", UriKind.Relative);
            else
                LangDict.Source = new Uri(@"Resource\Languages\EN.xaml", UriKind.Relative);

            Application.Current.Resources.MergedDictionaries[0] = LangDict;//资源赋值
        }

        /// <summary>
        /// 获取引导配置
        /// </summary>
        static void GuidanceConfig()
        {
            try
            {
                ProgramConfig.Instance.Guidance = bool.Parse(ConfigOperator.IniRead("System", "Guidance"));
            }
            catch
            {
                ConfigOperator.IniWrite("System", "Guidance", ProgramConfig.Instance.Guidance.ToString());
                ConfigOperator.IniWrite("System", "Guiding", ProgramConfig.Instance.Guiding.ToString());
            }
        }

        /// <summary>
        /// 获取主题色配置
        /// </summary>
        static void ThemeConfig()
        {
            try
            {
                string Theme = ConfigOperator.IniRead("System", "Theme");
                if (Theme != string.Empty)
                {
                    ProgramConfig.Instance.DefaultTheme = Theme;
                    //搜索列表对应资源
                    foreach (var ListItem in ProgramConfig.Instance.ThemeList.Keys)
                    {
                        if (ListItem.ToString() == ProgramConfig.Instance.DefaultTheme)
                        {
                            ResourceDictionary ThemeDict = new();
                            int index = ProgramConfig.Instance.ThemeList.IndexOfKey(ProgramConfig.Instance.DefaultTheme);

                            ThemeDict.Source = new Uri(
                                ProgramConfig.Instance.ThemeList.Values[index].ToString(),
                                UriKind.Relative
                                );
                            Application.Current.Resources.MergedDictionaries[1] = ThemeDict;//资源赋值
                            break;
                        }
                    }
                }
                else
                    ConfigOperator.IniWrite("System", "Theme", ProgramConfig.Instance.DefaultTheme);
            }
            catch (Exception ex)
            {
                Log.Write($"主题色获取/设置失败:{ex.Message}", LogType.Error);
            }
        }

        #region TitleBar        
        /// <summary> 功能页面引导 </summary>
        void Help_Click(object sender, RoutedEventArgs e)
        {
            ProgramConfig.Instance.Guiding = !ProgramConfig.Instance.Guiding;
            ConfigOperator.IniWrite("System", "Guiding", ProgramConfig.Instance.Guiding.ToString());
            Page PageContent = (Page)_NavigationFrame.Content;

            try
            {
                if (ProgramConfig.Instance.Guiding)
                {
                    PageContent.FindChild<Grid>("Settings_guide").Visibility = Visibility.Visible;
                    PageContent.FindChild<Grid>("Timeaxis_guide").Visibility = Visibility.Visible;
                }
                else
                {
                    PageContent.FindChild<Grid>("Settings_guide").Visibility = Visibility.Hidden;
                    PageContent.FindChild<Grid>("Timeaxis_guide").Visibility = Visibility.Hidden;
                }
            }
            catch (Exception ex)
            {
                Log.Write($"引导功能异常:{ex.Message}", LogType.Error);
            }

        }

        /// <summary>
        /// 保存按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Save_Click(object sender, RoutedEventArgs e)
        {
            SingleControls.Instance.ArmorStandPage.PageSaveFile(sender, e);
        }

        /// <summary>
        /// 设置按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Option_Click(object sender, RoutedEventArgs e)
        {
            _NavigationFrame.Navigate(SingleControls.Instance.OptionPage);
        }

        /// <summary>
        /// 关于按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void About_Click(object sender, RoutedEventArgs e)
        {
            _NavigationFrame.Navigate(SingleControls.Instance.AboutPage);
        }
        #endregion
    }
}
